//
//  WhiteListViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/2/22.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "WhiteListViewController.h"
#import "WhiteDetailViewController.h"

@interface WhiteLeaseListCell : XHBaseTableCell
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,strong) UILabel *nameLab;
@property (nonatomic,strong) UILabel*urlLab;
@end

@implementation WhiteLeaseListCell

- (void)setupUI{
    self.selectionStyle =  UITableViewCellSelectionStyleDefault;
    self.backView = [UIView new];
    self.backView.backgroundColor = UIColor.whiteColor;
    [self.backView.layer setLayerShadow:kShadowColor offset:CGSizeMake(0, 0) radius:6];
    self.backView.layer.cornerRadius = AdaptedWidth(10);
    [self.contentView addSubview:self.backView];
    
    self.nameLab = [UILabel new];
    self.nameLab.textColor = UIColorHex(#FFAE00);
    self.nameLab.font = kDefaultFont(15);
    [self.backView addSubview:self.nameLab];
    
    self.urlLab = [UILabel new];
    self.urlLab.textColor = UIColorHex(#333333);
    self.urlLab.font = kDefaultFont(13);
    [self.backView addSubview:self.urlLab];
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(15));
        make.right.mas_equalTo(AdaptedWidth(-15));
        make.top.mas_equalTo(AdaptedWidth(10));
        make.bottom.mas_equalTo(AdaptedWidth(-10));
    }];
    [self.nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(AdaptedWidth(15));
        make.left.mas_equalTo(kNormalSpace);
    }];
    [self.urlLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(AdaptedWidth(-15));
        make.left.mas_equalTo(kNormalSpace);
       make.right.mas_equalTo(-kNormalSpace);
    }];
    self.selectedBackgroundView = [UIView new];
    self.selectedBackgroundView.backgroundColor = UIColor.clearColor;
}
//处理选中背景色问题
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    if (!self.editing) {
        return;
    }
    [super setSelected:selected animated:animated];
    if (self.editing) {
        self.backView.backgroundColor = [UIColor whiteColor];
        self.nameLab.backgroundColor = [UIColor whiteColor];
        self.urlLab.backgroundColor = [UIColor whiteColor];
        self.contentView.backgroundColor = [UIColor clearColor];
        self.backgroundColor = [UIColor clearColor];
    }
}

-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    return;
}

@end

@interface WhiteBottomView : UIView

@property (nonatomic ,strong) UIButton *allBtn;
@property (nonatomic ,strong) UIButton *deleteBtn;

@end
@implementation WhiteBottomView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.allBtn];
        [self addSubview:self.deleteBtn];
    }
    return self;
}

- (UIButton *)allBtn{
    if (!_allBtn) {
        self.allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _allBtn.frame = CGRectMake(10, 0, 60, 49);
        _allBtn.titleLabel.font = kBoldFont(15);
        [_allBtn setTitle:XLocalized(@"全选") forState:UIControlStateNormal];
        [_allBtn setImage:IMAGE_NAMED(@"yellow_sel") forState:UIControlStateSelected];
        [_allBtn setImage:IMAGE_NAMED(@"yuan_unselect") forState:UIControlStateNormal];
        [_allBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
    }
    return _allBtn;
}

- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        self.deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteBtn.frame = CGRectMake(self.bounds.size.width - 70, 0, 60, 49);
        _deleteBtn.titleLabel.font = kBoldFont(15);
        [_deleteBtn setTitle:XLocalized(@"删除") forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:UIColorHex(999999) forState:UIControlStateDisabled];
    }
    return _deleteBtn;
}
@end

@interface WhiteListModel : NSObject
@property (nonatomic,strong) NSString*permissions;
@property (nonatomic,strong) NSMutableArray<DappInfo*>*dapps;
@end
@implementation WhiteListModel
- (NSMutableArray<DappInfo*>*)dapps{
    if (!_dapps) {
        _dapps = [NSMutableArray array];
    }
    return _dapps;
}
@end

@interface WhiteListViewController ()
@property (nonatomic,strong) WhiteBottomView *bottomView;
@property (nonatomic,assign) BOOL allChoose;
@property (nonatomic,strong) NSMutableArray *chooseArr;
@property (nonatomic,strong) NSMutableArray <WhiteListModel*>*dataArr;
@property (nonatomic,strong) NSMutableArray <DappInfo*>*orginData;
@property (nonatomic,assign) BOOL edit;
@property (nonatomic,weak) UIButton* rightBtn;

@end

@implementation WhiteListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated{
   [super viewWillAppear:animated];
   [self coginData];
}

- (void)coginData{
   [self.dataArr removeAllObjects];
    self.orginData = self.wallet.whiteDapps.mutableCopy;
    [self.orginData enumerateObjectsUsingBlock:^(DappInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        WhiteListModel*listM = [self.dataArr lastObject]?:[WhiteListModel new];
        if (!listM.permissions.length) {
            listM.permissions = obj.permissions;
        }
        if ([listM.permissions isEqualToString:obj.permissions]) {
            listM.permissions = obj.permissions;
            [listM.dapps addObject:obj];
            if (![self.dataArr containsObject:listM]) {
                [self.dataArr addObject:listM];
            }
        }else{
            WhiteListModel*listM = [WhiteListModel new];
            listM.permissions = obj.permissions;
            [listM.dapps addObject:obj];
            [self.dataArr addObject:listM];
        }
    }];
    [self.tableView reloadData];
}

- (void)setupUI{
    self.title = self.wallet.wallet_name;
    self.tableView.rowHeight = AdaptedWidth(90);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addNavigationItemWithTitles:@[@"编辑"] isLeft:NO target:self action:@selector(rightBtnClick:) tags:nil];
    [self.view addSubview:self.bottomView];
}
- (void)rightBtnClick:(UIButton*)btn{
   self.edit = !self.edit;
   if (btn) {
      _rightBtn = btn;
   }
   [_rightBtn setTitle:!self.edit?XLocalized(@"编辑"):XLocalized(@"取消") forState:UIControlStateNormal];
    if (self.tableView.isEditing) {
        [self.tableView setEditing:NO animated:YES];
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.bottomView.top = self.view.bottom;
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.bottomView.mas_top);
                [self.view layoutIfNeeded];
            }];
        } completion:nil];
    }else{
       [self.chooseArr removeAllObjects];
       self.bottomView.deleteBtn.enabled = self.chooseArr.count;
       self.bottomView.allBtn.selected = NO;
        [self.tableView setEditing:YES animated:YES];
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.bottomView.top = self.view.bottom-self.bottomView.height;
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.bottomView.mas_top);
                [self.view layoutIfNeeded];
            }];
        } completion:nil];
    }
}

- (void)viewWillLayoutSubviews{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.customNavigationBar.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
}

///删除
- (void)deleteData{
   for (NSIndexPath *indexPath in self.chooseArr) {
      DappInfo*dapp = [[self.dataArr objectAtIndex:indexPath.section].dapps objectOrNilAtIndex:indexPath.row];
      if ([self.orginData containsObject:dapp]) {
         [self.orginData removeObject:dapp];
         WhiteListModel*listM = [self.dataArr objectOrNilAtIndex:indexPath.section];
         if ([listM.dapps containsObject:dapp]) {
            [listM.dapps removeObject:dapp];
         }
      }
   }
   [self.chooseArr removeAllObjects];
   self.wallet.whiteDappJson = [self.orginData modelToJSONString];
   [[XHDataBaseManager shareInstance]updateWalletToDB:self.wallet];
   [self.tableView reloadData];
   [self rightBtnClick:nil];
   self.bottomView.deleteBtn.enabled =self.chooseArr.count;
}
///全选
- (void)tapAllBtn:(UIButton*)allBtn{
    allBtn.selected = !allBtn.selected;
    [self.chooseArr removeAllObjects];
    if (allBtn.selected) {
        for (int i = 0; i< self.dataArr.count; i++) {
            WhiteListModel*listM = self.dataArr[i];
            for (int j = 0; j<listM.dapps.count; j++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
                [self.chooseArr addObject:indexPath];
                [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            }
        }
    
    }else{
        for (int i = 0; i< self.dataArr.count; i++) {
            WhiteListModel*listM = self.dataArr[i];
            for (int j = 0; j<listM.dapps.count; j++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:j inSection:i];
                [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
            }
        }
    }
   self.bottomView.deleteBtn.enabled =self.chooseArr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArr objectAtIndex:section].dapps.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WhiteLeaseListCell *cell = [WhiteLeaseListCell cellForTableView:tableView];
    DappInfo*dapp = [[self.dataArr objectAtIndex:indexPath.section].dapps objectOrNilAtIndex:indexPath.row];
    cell.nameLab.text = dapp.title;
    cell.urlLab.text = dapp.address;
   if (tableView.isEditing) {
      if ([self.chooseArr containsObject:indexPath]) {
         [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
      }
   }
    return cell;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
   if (tableView.isEditing) {
      return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
   }else{
        return UITableViewCellEditingStyleDelete;
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        ///单个删除
        DappInfo*dapp = [[self.dataArr objectAtIndex:indexPath.section].dapps objectOrNilAtIndex:indexPath.row];
        if ([self.orginData containsObject:dapp]) {
            [self.orginData removeObject:dapp];
            self.wallet.whiteDappJson = [self.orginData modelToJSONString];
            [[XHDataBaseManager shareInstance]updateWalletToDB:self.wallet];
            WhiteListModel*listM = [self.dataArr objectOrNilAtIndex:indexPath.section];
            if ([listM.dapps containsObject:dapp]) {
                [listM.dapps removeObject:dapp];
            }
            [self.tableView reloadData];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.isEditing) {
        [self.chooseArr addObject:indexPath];
        self.bottomView.allBtn.selected = self.chooseArr.count==self.wallet.whiteDapps.count;
        self.bottomView.deleteBtn.enabled =self.chooseArr.count;
    }else{
       WhiteDetailViewController *vc = [WhiteDetailViewController new];
       vc.dappInfo = [[self.dataArr objectAtIndex:indexPath.section].dapps objectAtIndex:indexPath.row];
       vc.wallet =self.wallet;
       [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath  {
    if (tableView.isEditing) {
        [self.chooseArr removeObject:indexPath];
        self.bottomView.allBtn.selected = self.chooseArr.count==self.wallet.whiteDapps.count;
        self.bottomView.deleteBtn.enabled =self.chooseArr.count;
    }
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel*title = [UILabel new];
    title.textColor = UIColorHex(#FFAE00);
    title.font = kDefaultFont(16);
   title.text = [NSString stringWithFormat:@"  %@",self.dataArr[section].dapps.count?self.dataArr[section].permissions:@""];
    return title;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
   return self.dataArr[section].dapps.count?25.0:0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
   return 10.f;
}
#pragma mark - getter
- (WhiteBottomView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[WhiteBottomView alloc] initWithFrame:CGRectMake(0, self.view.bottom, self.view.width, kTabBarHeight)];
        _bottomView.backgroundColor = UIColorHex(#DDDDDD);
        [_bottomView.deleteBtn addTarget:self action:@selector(deleteData) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.allBtn addTarget:self action:@selector(tapAllBtn:) forControlEvents:UIControlEventTouchUpInside];
        _bottomView.deleteBtn.enabled = NO;
    }
    return _bottomView;
}
- (NSMutableArray*)chooseArr{
    if (!_chooseArr) {
        _chooseArr = [NSMutableArray array];
    }
    return _chooseArr;
}
- (NSMutableArray<WhiteListModel*>*)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
@end
